<template>
  <div class="goods-container" v-loading.fullscreen.lock="loading">
    <div class="normal-title-1">
      <div class="flex-1">
        <el-button v-if="goodsId" type="plain-third" @click="handleBack">
          {{$t('common.base.back')}}
        </el-button>
        <el-button type="primary" @click="handleSave" :loading="pending">
          {{$t('common.base.save')}}
        </el-button>
      </div>
    </div>

    <div class="base-form" v-if="init">
      <GoodsEditForm
        ref="goodsEditForm"
        :fields="_goodsFields"
        :goods-id="goodsId"
        v-model="form"
        :pending="pending"
        :is-edit="isEdit"
        @addNeedServerDeleFiles="addNeedServerDeleFiles"
      />
    </div>
  </div>
</template>

<script>
import _ from 'lodash';
import qs from '@src/util/querystring';
import { goodsFields, formatFields } from '@src/modules/linkc/field.js';
import GoodsEditForm from '@src/modules/linkc/goods/components/GoodsEditForm.vue';
import { editGoodsInfo, queryGoodsDetail } from '@src/api/PortalApi.ts';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import { querySpecsList } from '@src/api/LinkcApi';

export default {
  components: {
    GoodsEditForm,
  },
  data() {
    return {
      loading: false,
      init: true,
      pending: false,
      form: {},
      goodsFields: [],
      standArr: [],
      needServerDeleFiles: [],
    };
  },
  computed: {
    goodsId() {
      const queryObject = qs.parse(window.location.search);

      return queryObject.id ?? '';
    },
    action() {
      return this.goodsId ? 'edit' : 'create';
    },
    isEdit() {
      return this.action === 'edit';
    },
    _goodsFields() {
      this.goodsFields = _.cloneDeep(goodsFields);

      this.goodsFields.forEach(v => {
        if (v.fieldName === 'serviceType' && this.form?.originType === 2) {
          v.setting.dataSource = [{ text: this.$t('task.setting.taskTypeSetting.manage.industryNames.name7'), value: 2 }];
          v.disable = 1;
        }

        if (v.fieldName === 'originPrice') {
          if (this.form?.originType === 1) {
            v.placeHolder = this.$t('goods.edit.modifyPrice1')
          } else if (this.form?.originType === 2) {
            v.placeHolder = this.$t('goods.edit.modifyPrice2')
          } else {
            v.placeHolder = this.$t('goods.edit.modifyPrice3')
          }
        }
        if(v.fieldName === 'information') {
          v.maxlength = 1000
        }
      });
      return this.goodsFields.filter(field => field.isEdit);
    },
  },
  async mounted() {
    await this.getSpecsList()
    this.handleGetGoodsInfo();
  },
  methods: {
    getSpecsList() {
      querySpecsList().then(res => {
          if(res.code != 200) return this.$message.error(res.msg);
          this.standArr = (res.data || []).map(item => {
            return {
              name: item.specsName,
              fieldName: item.fieldName,
            }
          })
      }).catch(err => {
          this.$message.error(res.msg);
      })
    },
    async handleGetGoodsInfo() {
      try {
        this.loading = true;

        const { code, data } = await queryGoodsDetail({ id: this.goodsId });

        if (code !== '200') {
          this.loading = false;
          return this.$message.error(this.$t('goods.tips.obtainInfoFailed'));
        }

        this.handleConvertData(data);
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error('fetch goods Detail error', error);
      }
    },
    // 转换数据
    handleConvertData(data) {
      this.form = data;

      this.form.catalogIds = this.form?.productTypeList?.map(v => v.id) || [];
      this.form.priceType = this.form.priceType + '';

      if (this.form.inventoryNumber >= 0)
        this.form.inventoryNumber = this.form.inventoryNumber + '';

      if (this.form.expressCost >= 0)
        this.form.expressCost = this.form.expressCost + '';

      if (this.form.serviceType === 1) {
        this.form.serviceType = [this.$t('goods.component.expressDelivery')];
      } else if (this.form.serviceType === 2) {
        this.form.serviceType = [this.$t('task.setting.taskTypeSetting.manage.industryNames.name7')];
      } else {
        this.form.serviceType = [this.$t('goods.component.expressDelivery'), this.$t('task.setting.taskTypeSetting.manage.industryNames.name7')];
      }
      let { hasSpecs=0, specifications=[], specsList=[], standard=''} = this.form
      this.$set(this.form, 'standardDesc', {})
      if(specsList?.length) {
        specsList = specsList.map(items => {
          let obj = {}
          items.specsInfo.forEach(v => {
            obj[v.specsGroupName] = v.specsInfoValue
          })
          return {
            ...items,
            ...obj
          }
        })
      }
      this.form.standardDesc = {
        hasSpecs, 
        specifications, 
        specsList, 
        standard
      }
    },
    handleBack() {
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);

      openAccurateTab({
        type: PageRoutesTypeEnum.PageGoodsDetail,
        key: this.goodsId,
        titleKey: ` - ${this.form.commodityName}`,
        params: `id=${this.goodsId}`,
      });
    },
    handleSave() {
      this.$refs.goodsEditForm.validate().then(valid => {
        if (!valid) {
          return Promise.reject('validate fail.');
        }
        if(this.form?.standardDesc?.hasSpecs) {
          let specsData = this.form?.standardDesc?.specifications || []
          let specsList = this.form?.standardDesc?.specsList || []
          if(specsData.length ==0) return this.$message.error(this.$t('goods.tips.SpecsDescTip'));
          if(specsList.length) {
            let flag = false
            flag = specsList.some(item => ((item.inventory!=0 && !item.inventory) || !item.salePrice ))
            if(flag) return this.$message.error(this.$t('goods.tips.SpecsDescTip'));
            let serialNumberArr = specsList.filter(item => item?.serialNumber).map(v=> v?.serialNumber)
            flag = this.isRepeat(serialNumberArr)
            if(flag) return this.$message.error(this.$t('goods.tips.serialNumberTips'));
          }
        }
        this.handleSubmit();
      });
    },
    isRepeat(arr) {
      return new Set(arr).size !== arr.length;
    },
    handleBuildParams() {
      try {
        const params = _.cloneDeep(this.form);
        params.priceType = ~~params.priceType;
        if (params.priceType === 1) params.price = params.originPrice;
        if (params.serviceType?.length > 1) {
          params.serviceType = 3;
        } else {
          params.serviceType = params.serviceType[0] === this.$t('goods.component.expressDelivery') ? 1 : 2;
        }
        params.catalogIds =
          params.catalogPathIds?.map(item => item[item.length - 1]) || [];

        params.standard = params.standardDesc.standard
        params.hasSpecs = params.standardDesc.hasSpecs
        params.specifications = []
        params.specsList = []
        if(params?.standardDesc?.hasSpecs) {
          let keys = []
          if(params?.standardDesc?.specsList) {
            keys = Object.keys(params?.standardDesc?.specsList[0]) || []
            params.standardDesc.specsList?.forEach((v) => {
              if(!(v.specsInfo)) {
                const specsInfo = []
                this.standArr?.forEach(f => {
                  const obj = {};
                  if (keys.includes(f.name)) {
                    obj.specsGroupKey = f.fieldName;
                    obj.specsGroupName = f.name;
                    obj.specsInfoValue = v?.[f.name];
                  }
                  if (Object.keys(obj).length !== 0) specsInfo.push(obj);
                })
                let paramsObj = {
                  specsInfo,
                  serialNumber: v.serialNumber,
                  salePrice: v.salePrice,
                  inventory: v.inventory,
                }
                params.specsList.push(paramsObj)
              }else {
                params.specsList.push(v)
              }
            })
            params.standard = ''
            params.specifications = params.standardDesc.specifications
          }
        }else {
          params.standard = params.standardDesc.standard
          params.specsPrice = '0.01~0.01'
        }
      return params;
      }catch (error) {
        console.error( error);
      }
    },
    async handleSubmit() {
      try {
        const params = this.handleBuildParams();
        if (this.needServerDeleFiles.length) {
          params.deleteFiles = this.needServerDeleFiles
        }
        const { code, msg } = await editGoodsInfo(params);

        if (code !== '200') {
          this.loading = false;
          return this.$message.error(msg);
        }

        this.$message.success(this.$t('goods.tips.modifySuccess'));
        setTimeout(() => {
          let id = window.frameElement.dataset.id;
          this.$platform.closeTab(id);

          this.handleBack();

          let fromId = window.frameElement.getAttribute('fromid');
          this.$platform.refreshTab(fromId);
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.error('fetch goods Detail error', error);
      }
    },
    addNeedServerDeleFiles(files) {
      this.needServerDeleFiles = [...this.needServerDeleFiles, ...files];
    },  
  },
};
</script>

<style lang="scss">
body {
  padding: 10px;
}

.goods-container {
  width: 100%;
  background-color: #fff;
  border-radius: 4px;

  .page-title {
    border-bottom: 1px solid #f4f7f5;
    padding: 12px 10px;
    display: flex;
    justify-content: space-between;

    .iconfont {
      font-size: 12px;
    }

    .title {
      display: flex;
      justify-content: space-between;
      span.text {
        line-height: 34px;
        margin-right: 12px;
      }
    }
  }

  @mixin title-class {
    height: 48px;
    display: flex;
    align-items: center;
    padding: 0 20px;
    font-weight: 600;
  }
  .normal-title-1 {
    @include title-class();
    padding: 12px 10px;
    height: auto;
    font-size: 20px;
    border-bottom: 1px solid #f4f7f5;
  }
}

.form-builder {
  margin: 0 auto;
  width: 700px;
  padding: 10px 0 0 10px;

  .input-and-btn {
    display: flex !important;
    flex-flow: row nowrap;

    .form-item,
    .form-text,
    .form-select,
    .biz-team-select {
      flex: 1;
    }

    .base-dist-picker {
      padding-right: 0;
    }

    button {
      margin-left: 10px;
    }
  }
}
</style>
